package com.sense.kukoo.biz_media.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.model.BaseMvvmModel
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.biz.MediaHistoryItemBean
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.common.repo.http.bean.ListenRecordBean

class MediaHistoryViewModel: BaseViewModel() {

    private val TAG: String = javaClass.simpleName

    private var mPageIndex = 2
    private val mPageSize = 10
    private var errorRetry: ()->Unit = {}
    private val mListenList: ArrayList<ListenRecordBean> = arrayListOf()

    private var mPlayState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var mCurrentMusicState: Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var mCurrentMusicProgress: Int = 1

    val action_back: MutableLiveData<Boolean> = MutableLiveData()
    val action_finishRefresh: MutableLiveData<Boolean> = MutableLiveData()
    val action_finishLoadMore: MutableLiveData<Boolean> = MutableLiveData()
    val action_showCleanAllDialog: MutableLiveData<Boolean> = MutableLiveData()
    val action_networkError: MutableLiveData<Boolean> = MutableLiveData()
    val data_enableLoadMore:MutableLiveData<Boolean> = MutableLiveData()
    val data_listenPage:MutableLiveData<ArrayList<MediaHistoryItemBean>> = MutableLiveData()
    val data_currentMusic:MutableLiveData<LocalMediaListItemBean> = MutableLiveData()
    val data_currentPercent:MutableLiveData<Int> = MutableLiveData()
    val data_currentState:MutableLiveData<Int> = MutableLiveData()

    override fun createModel(): BaseMvvmModel? = null

    override fun initData() {
        refreshListenPage()
        Kukoo.watcher.register(mWatcher)
    }

    fun onBack(){
        action_back.postValue(true)
    }

    fun onCleanAllClick(){
        action_showCleanAllDialog.postValue(true)
    }

    fun onMediaDelete(bean: MediaHistoryItemBean){
        toView(ACTION_SHOW_DIALOG)
        request {
            val contentId = bean.data.contentId
            val id = bean.data.id
            val ids = arrayOf(id)
            val result = Repo.http.listenDelete(ids)
            if (result.isSuccess() && true == result.data) {
                //
                var position = -1
                mListenList.forEachIndexed { index, listenRecordBean ->
                    if(contentId == listenRecordBean.contentId){
                        position = index
                    }
                }
                if(position != -1){
                    mListenList.removeAt(position)
                    showListenPageData()
                }
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun onMediaDeleteAll(){
        toView(ACTION_SHOW_DIALOG)
        request {
            val result = Repo.http.listenClean()
            if (result.isSuccess() && true == result.data) {
                //
                mListenList.clear()
                showListenPageData()
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun onMediaPlayClick(bean: MediaHistoryItemBean){
        val contentId = bean.data.contentId
        val currentPlayMusic = Kukoo.play.getCurrentPlayMusic()
        if(currentPlayMusic?.idOfChapter() == contentId){
            //当前的
            when (mPlayState) {
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_SEEKING,
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_PLAYING -> {
                    Kukoo.input.pause()
                }
                else -> {
                    Kukoo.input.start()
                }
            }
        }else{
            //非当前的
            request {
                val contentInfo = Repo.http.contentInfo(contentId)
                if (contentInfo.isSuccess()) {
                    val contentInfoData = contentInfo.data!!
                    val indexContentBean = IndexContentBean.formate(contentInfoData)
                    Kukoo.input.play(LocalMediaListItemBean(indexContentBean))
                } else {
                    Log.e(TAG, "result=" + contentInfo.msg)
                    contentInfo.msg.let { sendHintMessage(it) }
                }
            }
        }
    }

    fun showListenPageData(){
        val list: ArrayList<MediaHistoryItemBean> = arrayListOf()
        mListenList.forEach {
            list.add(MediaHistoryItemBean(data = it))
        }
        data_listenPage.postValue(list)
        //
        action_finishRefresh.postValue(true)
        action_finishLoadMore.postValue(true)
    }

    fun refreshListenPage(){
        val onError: (error: Throwable) -> Unit = {
            it.printStackTrace()
            errorRetry = {refreshListenPage()}
            action_networkError.postValue(true)
        }
        request(onError) {
            val result = Repo.http.listenPage(1, mPageSize)
            if (result.isSuccess()) {
                result.data?.let {
                    mPageIndex = 2
                    mListenList.clear()
                    mListenList.addAll(it)
                    if(it.size < mPageSize){
                        data_enableLoadMore.postValue(false)
                    } else {
                        data_enableLoadMore.postValue(true)
                    }
                    showListenPageData()
                }
            } else {
                Log.e(TAG, "result=" + result.msg)
                errorRetry = {refreshListenPage()}
                action_networkError.postValue(true)
            }
        }
    }

    fun loadMoreListenPage(){
        val onError: (error: Throwable) -> Unit = {
            it.printStackTrace()
            errorRetry = {loadMoreListenPage()}
            action_networkError.postValue(true)
            toView(ACTION_HIDE_DIALOG)
        }
        request(onError) {
            val result = Repo.http.listenPage(mPageIndex, mPageSize)
            if (result.isSuccess()) {
                result.data?.let { data ->
                    mPageIndex++
                    mListenList.addAll(data)
                    if(data.size < mPageSize){
                        data_enableLoadMore.postValue(false)
                    }
                    showListenPageData()
                }
            } else {
                Log.e(TAG, "result=" + result.msg)
                errorRetry = {loadMoreListenPage()}
                action_networkError.postValue(true)
            }
        }
    }

    fun onErrorRetry(){
        errorRetry()
    }

    override fun onCleared() {
        super.onCleared()
        Kukoo.watcher.unregister(mWatcher)
    }

    private val mWatcher = object: UserWatcher.MusicStateWatcher{
        override fun onMusicChanged(music: LocalMediaListItemBean) {
            data_currentMusic.postValue(music)
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {}

        override fun onPlayPercentChanged(percent: Int) {
            if(mCurrentMusicProgress != percent){
                mCurrentMusicProgress = percent
                data_currentPercent.postValue(percent)
            }
        }

        override fun onPlayStateChanged(state: Int) {
            mPlayState = state
            if(mCurrentMusicState != state){
                mCurrentMusicState = state
                data_currentState.postValue(state)
            }
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

}